/*
@file 流量上报
@author <AA>
@version 20160520
 */

(function() {
  var slice = [].slice;

  (function(definition, undef) {
    var $, exports, global, i, t;
    global = this;
    $ = global.jQuery;
    exports = {};
    definition(global, exports, $);
    for (i in exports) {
      global[i] = exports[i];

    }
    t = exports.tracking;
    t({
      '': [t.dtime, t.baseParams, t.tos, t.sessionId, t.useragent, t.cid, t.ipaddress, t.href]
    });
  })
  
  (function(global, exports, $) {
    var iarr = [], _key=0;
    var crossdomainGet, doc, domReady, flush, fns, hack, loaded, loc, protocol, testEl, topDomain, tracking;
    doc = global.document;
    loc = global.location;
    protocol = loc.protocol.substr(0, 4) === 'http' ? '' : 'http:';
    fns = [];
    testEl = doc.documentElement;
    hack = testEl.doScroll;
    loaded = (/^loaded|c/).test(doc['readyState']);
    flush = function() {
      var f;
      loaded = 1;
      while (f = fns.shift()) {
        f();
      }
    };
    if (typeof doc.addEventListener === "function") {
      doc.addEventListener('DOMContentLoaded', function() {
        doc.removeEventListener('DOMContentLoaded', arguments.callee, false);
        flush();
      });
    }
    domReady = function(fn) {
      if (loaded) {
        fn();
      } else {
        fns.push(fn);
      }
    };
    topDomain = function(d) {
      return /\.?([a-z0-9\-]+\.[a-z0-9\-]+)(:\d+)?$/.exec(d)[1];
    };

    /*
    跟踪函数tracking
    @param {Object} opts 定义要收集的信息
     */
    exports.tracking = tracking = function(opts) {
      domReady(function() {
        var data, i, j, k, len, len1, opt, ref;
        data = {};
        ref = [opts[loc.host], opts['']];
        for (j = 0, len = ref.length; j < len; j++) {
          opt = ref[j];
          if (opt) {
            if (typeof opt === 'function') {
              opt(data);
            } else {
              for (k = 0, len1 = opt.length; k < len1; k++) {
                i = opt[k];
                if (typeof i === "function") {
                  i(data);
                }
              }
            }
          }
        }
        crossdomainGet(data);
      });
    };

    /*    附加基本的参数到数据上，包括referrer user_name x-acl-token     */
    tracking.baseParams = function(data) {
      var ref, ref1, ref2, ref3, ref4;
      //data.user_name = ((ref2 = /(; )?(UserName)=([^;]+)/.exec(doc.cookie)) != null ? ref2[3] : void 0) || '';
    data.userId = ((ref2 = /(; )?(userId)=([^;]+)/.exec(doc.cookie)) != null ? ref2[3] : void 0) || '-';
    if(typeof(VCG)!="undefined"){
      data.user_name = VCG.userName;
    }else{
      data.user_name = "-";
    }
      return data.ref = doc.referrer;
    };
    tracking.sessionId = function(data) {
      var ref, sid;
      sid = (ref = /\bdc_session_id=([^;]*)(?:$|;)/.exec(doc.cookie)) != null ? ref[1] : void 0;
      if (sid === void 0 || !/^\d+$/.test(sid)) {
        sid = +new Date();
      }
      //doc.cookie = "dc_session_id=" + sid + " ; path=/ ; domain=." + (topDomain(loc.host));
    doc.cookie = "dc_session_id=" + sid ;
      return data.session_id = "" + sid;
    };
  
    /*    附加上一页面及停留时间到数据上     */
    tracking.tos = function(data) {
      var e, now, ref, t, tos;
      now = +new Date() / 1000 | 0;
      t = (ref = /\bdc_tos=([^;]*)(?:$|;)/.exec(doc.cookie)) != null ? ref[1] : void 0;
      try {
        tos = now - parseInt(t, 36);
      } catch (_error) {
        e = _error;
        tos = -1;
      }
      //doc.cookie = "dc_tos=" + (now.toString(36)) + " ; expires=" + (new Date((now + 4 * 60 * 60) * 1000).toGMTString()) + " ; max-age=" + (4 * 60 * 60) + " ; path=/ ; domain=." + (topDomain(loc.host));
      doc.cookie = "dc_tos=" + (now.toString(36)) + " ; expires=" + (new Date((now + 4 * 60 * 60) * 1000).toGMTString()) + " ; max-age=" + (4 * 60 * 60);
    return data.tos = tos;
    };

    /*    附加浏览器参数到数据上的函数    */
    tracking.useragent=function(data){
      var ua = window.navigator.userAgent.toLowerCase();
      if(typeof(ua)!="undefined"){
          data.useragent=ua;
      }else{
        return data.useragent="-";
      }
    };
  
  /*    附加cookieID到数据上的函数     */
    tracking.cid=function(data){
    return data.cid = ((ref2 = /(; )?(JSESSIONID)=([^;]+)/.exec(doc.cookie)) != null ? ref2[3] : void 0) || '-';
    };

  /*    附加IP地址到数据上的函数     */
    tracking.ipaddress=function(data){
    var ipaddress = returnCitySN["cip"];
    if(typeof(ipaddress)!="undefined"){
      data.ipaddress=ipaddress;
    }else{
      return data.ipaddress="-";
    }
    };

  /*    附加当前url到数据上的函数     */
    tracking.href=function(data){
    var curl = loc.href;
    if(typeof(curl)!="undefined"){
      data.curl=curl;
    }else{
      return data.curl="-";
    }
    };

  //时间格式整理
  function date2str(dtime,dtype) { 
    var z = {M:dtime.getMonth()+1,d:dtime.getDate(),h:dtime.getHours(),m:dtime.getMinutes(),s:dtime.getSeconds()}; 
    dtype = dtype.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)}); 
    dtype = dtype.replace(/y+/g,dtime.getFullYear());
    return dtype;
  }

  //取得当前时间
    tracking.dtime=function(data){
    var dtime = date2str(new Date(),"yyyy-MM-dd hh:mm:ss");
    if(typeof(dtime)!="undefined"){
      data.dtime=dtime;
    }else{
      return data.dtime="-";
    }
    };

    /*
    发送跨域HTTP GET请求
    @param {String} url - 请求的Url，忽略将使用默认的行为跟踪地址
    @param {Object} data - 请求要提交的数据
     */
    return tracking.crossdomainGet = crossdomainGet = function(data) {
    var i, p;
    data[Math.random() * 10000 | 0] = '';
  
    var ik = iarr.push(new Image()) - 1;
    data['x-acl-token']='QQToken';
    iarr[ik].onload = iarr[ik].onerror = function() {
      var _a = ik;
      iarr[_a].onload = iarr[_a].onerror = null;
      iarr[_a].removeAttribute("src");
      return iarr[_a] = null;
    };

    var sendData = ((function() {
          var results;
          results = [];
          for (p in data) {
            results.push(encodeURIComponent(p) + ':' + encodeURIComponent(data[p]));
          }
          return results;
        })()).join('#');
    var dataJson = [],headersObj = {};
    var headObj = {};
    headObj.comp="vcg_designer_user_profile";
    headObj.pv="track";
    headersObj.headers = headObj;
    headersObj.body = sendData;
    dataJson.push(headersObj);
    $.ajax({
        url : "https://track-vcg-community.csdn.net",
        type : 'POST',
        data : JSON.stringify(dataJson),
        dataType : 'json',
        //contentType : 'application/json',
        success : function(data, status, xhr) {
        },
        Error : function(xhr, error, exception) {
            // handle the error.
            alert(exception.toString());
      }
      }); 
    };
  });
}).call(this);